
const loginController = function($state, AuthService) {
  'ngInject';

  const vm = this;

  vm.loginForm = {
    username: '',
    password: '',
    remember: false
  };

  vm.isLoading = false;
  vm.errorMessage = '';

  // 预设的演示账号
  vm.demoAccounts = [
    { username: 'admin', password: 'admin123', role: '管理员' },
    { username: 'user', password: 'user123', role: '普通用户' },
    { username: 'user1', password: 'user123', role: '普通用户1' },
    { username: 'operator', password: 'op1234', role: '操作员' },
    { username: 'operator1', password: 'op1234', role: '操作员1' },
    { username: 'support1', password: 'support123', role: '技术支持' }
  ];

  vm.login = function() {
    // 在组件中，表单可以通过 this.loginFormElement 或者跳过验证直接进行后端验证
    if (!vm.loginForm.username || !vm.loginForm.password) {
      vm.errorMessage = '请填写完整的登录信息';
      return;
    }

    vm.isLoading = true;
    vm.errorMessage = '';

    // 调用后端登录API
    AuthService.login(vm.loginForm.username, vm.loginForm.password)
      .then(result => {
        if (result.success) {
          // 登录成功，跳转到首页
          $state.go('app.home');
        } else {
          vm.errorMessage = result.message;
        }
      })
      .catch(error => {
        vm.errorMessage = error.message || '登录失败，请重试';
      })
      .finally(() => {
        vm.isLoading = false;
      });
  };

  vm.fillDemoAccount = function(account) {
    vm.loginForm.username = account.username;
    vm.loginForm.password = account.password;
    vm.errorMessage = '';
  };

  vm.resetForm = function() {
    vm.loginForm = {
      username: '',
      password: '',
      remember: false
    };
    vm.errorMessage = '';
  };

  // 检查是否已经登录
  vm.$onInit = function() {
    if (AuthService.isLoggedIn()) {
      $state.go('app.home');
    }
  };
};

const loginComponent = {
  templateUrl: 'src/app/pages/login/login.template.html',
  controller: loginController
};

function initLoginController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化登录控制器模块');
    return;
  }

  angular.module('app.pages.login', [])
    .component('loginPage', loginComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initLoginController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initLoginController();
}